<template>
  <div class="profile">
    <div class="profile-header">
      <div class="profile-avatar">
        <img
          :src="userInfo?.avatar"
          alt="Avatar"
        />
      </div>

      <div class="profile-info">
        <div class="profile-name">{{ userInfo?.nickname }}</div>
        <div class="profile-signature">{{ userInfo?.signature }}</div>
        <div class="profile-gender">
          <span class="profile-gender-label">性别：</span>
          <span class="profile-gender-value">{{ getSex(userInfo?.sex) }}</span>
        </div>
        <div class="profile-follow">
          <div
            class="profile-follow-count"
            @click="activeTab = 'follow'"
          >
            <span class="profile-follow-count-label">关注</span>
            <span class="profile-follow-count-value">{{
              formatNumber(userInfo?.followCount) || 0
            }}</span>
          </div>

          <div
            class="profile-follow-count"
            @click="activeTab = 'fans'"
          >
            <span class="profile-follow-count-label">粉丝</span>
            <span class="profile-follow-count-value">{{
              formatNumber(userInfo?.fansCount) || 0
            }}</span>
          </div>
        </div>

        <div
          class="profile-action"
          v-if="!isCurrentUser"
        >
          <div class="subscribe-btn">
            <a-button
              type="primary"
              class="subscribe-btn-text"
              @mouseenter="handleSubscribeMouseenter"
              @mouseleave="handleSubscribeMouseleave"
              @click="subscribe"
            >
              {{ subscribeText }}
            </a-button>
          </div>

          <div
            class="chat-btn"
            @click="locateToMessage"
          >
            <a-button class="chat-btn-text"> 私信 </a-button>
          </div>
        </div>
      </div>
    </div>

    <div class="tabs">
      <div
        v-for="tab in tabs"
        :key="tab.key"
        class="tab"
        :class="{ active: activeTab === tab.key }"
        @click="activeTab = tab.key"
      >
        {{ tab.title }}
      </div>
    </div>

    <div class="content">
      <Video
        v-if="activeTab === 'videos'"
        v-model="videoList"
        v-model:queryParams="videoQueryParams"
        v-model:total="videoListTotal"
        @getList="getVideoList"
      />

      <Collection
        v-else-if="activeTab === 'collections'"
        v-model="collectionList"
        v-model:queryParams="collectionQueryParams"
        v-model:total="collectionListTotal"
        @getList="getCollectionList"
      />

      <Setting
        v-else-if="activeTab === 'setting' && isCurrentUser"
        v-model="userInfo"
      />

      <FansList
        v-else-if="activeTab === 'fans'"
        v-model="currentUserId"
      />

      <FollowList
        v-else-if="activeTab === 'follow'"
        v-model="currentUserId"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import Video from './components/videoList/index.vue'
import Collection from './components/collectionList/index.vue'
import Setting from './components/setting/index.vue'
import FansList from './components/fansList/index.vue'
import FollowList from './components/followList/index.vue'
import { useUserStore } from '@/store/modules/user'
import { getUserProfile } from '@/api/user'
import { PlatformUserProfileRespVO } from '@/types/user'
import { sexOptions } from '@/utils/options'
import { CvVideoItemRespVO } from '@/types/global'
import { getUserProfileVideoList } from '@/api/video'
import { CvVideoProfileReqVO } from '@/types/profile'
import { CvVideoCollectionPageReqVO, CvVideoCollectionRespVO } from '@/types/collection'
import { getCollectionPage } from '@/api/collection'
import { cancelSubscribe, getSubscribe, saveSubscribe } from '@/api/subscribe'
import { message } from 'ant-design-vue'
import { CvSubscribeDetailRespVO, CvSubscribeSaveReqVO } from '@/types/subscribe'
import { getAccessToken } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

const userStore = useUserStore()
const isCurrentUser = computed(() => {
  return userStore.getUserId == route.query.userId
})
const currentUserId = ref('')

/**
 * 订阅状态
 */
const subscribeDetail = ref<CvSubscribeDetailRespVO>()
const subscribeText = ref('关注')
const isSubscribed = ref(false)

onMounted(async () => {
  if (!route.query.userId || isNaN(Number(route.query.userId))) {
    await router.push({ path: '/404' })
    return
  }

  currentUserId.value = route.query.userId as string
  videoQueryParams.value.userId = currentUserId.value
  collectionQueryParams.value.userId = currentUserId.value
  userInfo.value = await getUserProfile(currentUserId.value)
  await getVideoList()

  if (currentUserId.value == userStore.getUserId) {
    tabs.value.push({
      key: 'setting',
      title: '设置'
    })
  }

  if (getAccessToken()) {
    subscribeDetail.value = await getSubscribe(currentUserId.value)
    if (subscribeDetail.value) {
      isSubscribed.value = true
      subscribeText.value = '已关注'
    }
  }
})

const userInfo = ref<PlatformUserProfileRespVO>()

/**
 * 订阅
 */
const subscribe = async () => {
  if (!getAccessToken()) {
    message.error('请登录')
    return
  }

  if (isSubscribed.value) {
    // 取消订阅
    await cancelSubscribe(subscribeDetail.value?.id as number)
    subscribeText.value = '关注'
    isSubscribed.value = false
    message.success('取关成功')
  } else {
    // 订阅
    await saveSubscribe(<CvSubscribeSaveReqVO>{
      targetUserId: currentUserId.value
    })
    subscribeDetail.value = await getSubscribe(currentUserId.value)
    subscribeText.value = '已关注'
    isSubscribed.value = true
    message.success('关注成功')
  }
}

/**
 * 订阅按钮进入事件
 */
const handleSubscribeMouseenter = () => {
  if (isSubscribed.value) {
    subscribeText.value = '取消关注'
  } else {
    subscribeText.value = '关注'
  }
}

/**
 * 订阅按钮离开事件
 */
const handleSubscribeMouseleave = () => {
  if (!isSubscribed.value) {
    subscribeText.value = '关注'
  } else {
    subscribeText.value = '已关注'
  }
}

/**
 * 跳转到私信页
 */
const locateToMessage = () => {
  if (!getAccessToken()) {
    message.error('请登录')
    return
  }

  router.push({
    path: '/message',
    query: {
      userId: currentUserId.value
    }
  })
}

/**
 * 播放量格式化
 */
const formatNumber = (num: number) => {
  if (!num) {
    return 0
  }

  if (num >= 1000 && num < 10000) {
    return (num / 1000).toFixed(1) + 'K'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'W'
  } else {
    return num.toString()
  }
}

/**
 * 获取性别
 */
const getSex = (value: number) => {
  for (let item of sexOptions) {
    if (item.value == value) {
      return item.label
    }
  }
  return '未知'
}

// ==================== 视频列表 ====================
const videoList = ref<CvVideoItemRespVO[]>([])
const videoListTotal = ref(0)

const videoQueryParams = ref<CvVideoProfileReqVO>({
  userId: 0,
  title: '',
  pageNo: 1,
  pageSize: 10
})

const getVideoList = async () => {
  const res = await getUserProfileVideoList(videoQueryParams.value)
  videoList.value = res.list
  videoListTotal.value = res.total
}

// ==================== 合集列表 ====================

const collectionQueryParams = ref<CvVideoCollectionPageReqVO>({
  userId: 0,
  title: '',
  pageNo: 1,
  pageSize: 10
})

const collectionList = ref<CvVideoCollectionRespVO[]>([])
const collectionListTotal = ref(0)

/**
 * 获取合集列表
 */
const getCollectionList = async () => {
  const res = await getCollectionPage(collectionQueryParams.value)
  collectionList.value = res.list
  collectionListTotal.value = res.total
}

// ==================== tabs ====================

const activeTab = ref('videos')
const tabs = ref([
  { key: 'videos', title: isCurrentUser.value ? '我的视频' : 'TA的视频' },
  { key: 'collections', title: isCurrentUser.value ? '我的合集' : 'TA的合集' }
])

watch(
  () => activeTab.value,
  async () => {
    if (activeTab.value === 'videos') {
      await getVideoList()
    } else if (activeTab.value === 'collections') {
      await getCollectionList()
    }
  }
)
</script>

<style scoped>
.profile {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 40px;
}

.profile-avatar img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 20px;
}

.profile-info {
  text-align: center;
}

.profile-name {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.profile-signature {
  font-size: 16px;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #666;
}

.profile-gender {
  font-size: 14px;
  margin-bottom: 10px;
}

.profile-gender-label {
  font-size: 12px;
}

.profile-follow {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 20px;
  margin-bottom: 20px;
}

.profile-follow-count {
  cursor: pointer;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
}

.profile-follow-count:hover {
  color: #69b1ff;
}

.profile-follow-count-label {
  font-size: 12px;
  display: flex;
  align-items: flex-end;
}

.profile-follow-count-value {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: flex-end;
}

.profile-action {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.subscribe-btn button,
.chat-btn button {
  width: 100px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #ccc;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
}

.tab.active {
  border-bottom: 2px solid #000;
}

.content {
  margin-top: 20px;
}
</style>
